/*
 * Copyright (c) 2011
 * Huawei.shen@gmail.com All rights reserved
 *
 * This file is a part os Iplite46 software which is a lightweight IPv4/IPv6
 * protocol stack.
 * 
 * !@file: order_case.c
 *   describtion:
 *   A simple implemenation of standard c library function 'hton*' 'ntoh*'
 */
#include "utils.h"

static UINT8 __order_byte = __LITE_BO_UNKNOWN__;

static inline void __test_host_order(void)
{
    if (__order_byte == __LITE_BO_UNKNOWN__)
    {
        unsigned int _test_unit_ = 1;
        if (*(unsigned char*)(&_test_unit_) == 1)
            __order_byte = __LITE_BO_LSB__;
        else
            __order_byte = __LITE_BO_MSB__;
    }
    
    return;
}

UINT32 _lite_htonl (UINT32 hostlong)
{
    __test_host_order();
    if(__order_byte == __LITE_BO_MSB__)
        return hostlong;
    else
        return (hostlong >> 24) |
            ((hostlong >> 8) & 0xFF00) |
            ((hostlong << 8) & 0xFF0000) |
            ( hostlong << 24);
}

UINT16 _lite_htons (UINT16 hostshort)
{
    __test_host_order();
    if(__order_byte == __LITE_BO_MSB__)
        return hostshort;
    else
        return (hostshort >> 8) |
            (hostshort << 8);
}

UINT32 _lite_ntohl (UINT32 netlong)
{
    __test_host_order();
    if(__order_byte == __LITE_BO_MSB__)
        return netlong;
    else
        return (netlong >> 24) |
            ((netlong >> 8) & 0xFF0000) |
            ((netlong << 8) & 0xFF00) |
            ((netlong << 24));
}

UINT16 _lite_ntohs (UINT16 netshort)
{
    __test_host_order();
    if(__order_byte == __LITE_BO_MSB__)
        return netshort;
    else
        return (netshort >>8) |
            (netshort << 8);
}
